# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql

# 存储到mysql数据库
class MysqlPipeline:
    def __init__(self):
        self.coon = pymysql.connect(
            host="127.0.0.1",  # 代表本机地址
            port=3306,
            user="root",
            password="15096962415",
            db="13_class"
        )

        # 建立游标，传递python给mysql的命令
        self.cursor = self.coon.cursor()

    def process_item(self, item, spider):
        try:
           sql = "insert into poem_data(poet,poem_title,content) values (%s,%s,%s)"
           param = [(item["poet"], item["poem_title"], item["content"])]
           self.cursor.executemany(sql, param)
           self.coon.commit()

        except Exception as e:
            print(e)
            self.coon.rollback()

        finally:
            return item

